#!/bin/bash
# vim: set ft=sh

set -e

<%
  require "shellwords"

  def esc(x)
    Shellwords.shellescape(x)
  end
%>

RUN_DIR=/var/vcap/sys/run/atc
LOG_DIR=/var/vcap/sys/log/atc
SIGNING_KEY=/var/vcap/packages/generated_signing_key/id_rsa
PIDFILE=$RUN_DIR/atc.pid
CF_CA_CERT=/var/vcap/jobs/atc/config/cf_ca_cert

source /var/vcap/packages/pid_utils/pid_utils.sh

<%
  postgres_addr = ""
  postgres_role_name = ""
  postgres_role_password = ""
  postgres_database = ""

  if_p("postgresql.address", "postgresql.role.name", "postgresql.role.password", "postgresql.database") do |addr, rn, rp, db|
    postgres_addr = addr
    postgres_role_name = rn
    postgres_role_password = rp
    postgres_database = db
  end

  if postgres_addr.empty?
    db = link("db")

    postgres_addr = "#{db.instances.first.address}:#{db.p("bind_port")}"
    postgres_database = p("postgresql_database")

    postgres_db = db.p("databases").find { |db| db["name"] == postgres_database }
    if postgres_db.nil?
      raise "database '#{db_name}' not provided by 'postgresql' link"
    end

    postgres_role_name = postgres_db["role"]
    postgres_role_password = postgres_db["password"]
  end
%>

case $1 in

  start)
    pid_guard $PIDFILE "atc"

    mkdir -p $RUN_DIR
    chown -R vcap:vcap $RUN_DIR

    mkdir -p $LOG_DIR
    chown -R vcap:vcap $LOG_DIR

    echo $$ > /var/vcap/sys/run/atc/atc.pid

    chown vcap:vcap $SIGNING_KEY
    chmod 0400 $SIGNING_KEY

    chown vcap:vcap $CF_CA_CERT
    chmod 0400 $CF_CA_CERT

    setcap cap_net_bind_service=+ep /var/vcap/packages/atc/bin/atc

    exec chpst -u vcap:vcap /var/vcap/packages/atc/bin/atc \
      --bind-ip <%= p("bind_ip") %> \
      --bind-port <%= p("bind_port") %> \
      <% if_p("tls_bind_port", "tls_cert", "tls_key") do |port, _, _| %> \
      --tls-bind-port <%= port %> \
      --tls-cert /var/vcap/jobs/atc/config/tls_cert \
      --tls-key /var/vcap/jobs/atc/config/tls_key \
      <% end %> \
      --peer-url <%= p("peer_url", "http://#{spec.address}:#{p("bind_port")}") %> \
      --external-url <%= esc(p("external_url")) %> \
      --postgres-data-source <%= esc("postgres://#{postgres_role_name}:#{postgres_role_password}@#{postgres_addr}/#{postgres_database}?sslmode=disable") %> \
      <% if p("development_mode") %> \
      --development-mode \
      <% end %> \
      <% if p("log_db_queries") %> \
      --log-db-queries \
      <% end %> \
      <% if p("allow_self_signed_certificates") %> \
      --allow-self-signed-certificates \
      <% end %> \
      --basic-auth-username <%= esc(p("basic_auth_username")) %> \
      --basic-auth-password <%= esc(p("basic_auth_password")) %> \
      --auth-duration <%= p("auth_duration") %> \
      <% p("github_auth.authorize").each do |a| %> \
        <% if org = a["organization"] %> \
          <% if a["teams"] == "all" %> \
      --github-auth-organization <%= esc(org) %> \
          <% elsif a["teams"].respond_to?(:each) %> \
            <% a["teams"].each do |team| %> \
      --github-auth-team <%= esc("#{org}/#{team}") %> \
            <% end %> \
          <% elsif a["teams"].nil? %> \
            <% raise "teams for organization '#{org}' must be specified; use 'all' for all teams" %> \
          <% else %> \
            <% raise "invalid teams for organization '#{org}': '#{a["teams"].inspect}" %> \
          <% end %> \
        <% elsif user = a["user"] %> \
      --github-auth-user <%= esc(user) %> \
        <% else %> \
          <% raise "organization or user not specified" %> \
        <% end %> \
      <% end %> \
      --github-auth-client-id <%= esc(p("github_auth.client_id")) %> \
      --github-auth-client-secret <%= esc(p("github_auth.client_secret")) %> \
      <% if_p("github_auth.auth_url") do |url| %> \
      --github-auth-auth-url <%= esc(url) %> \
      <% end %> \
      <% if_p("github_auth.token_url") do |url| %> \
      --github-auth-token-url <%= esc(url) %> \
      <% end %> \
      <% if_p("github_auth.api_url") do |url| %> \
      --github-auth-api-url <%= esc(url) %> \
      <% end %> \
      --uaa-auth-client-id <%= esc(p("uaa_auth.client_id")) %> \
      --uaa-auth-client-secret <%= esc(p("uaa_auth.client_secret")) %> \
      --uaa-auth-auth-url <%= esc(p("uaa_auth.auth_url")) %> \
      --uaa-auth-token-url <%= esc(p("uaa_auth.token_url")) %> \
      <% p("uaa_auth.cf_spaces").each do |s| %> \
      --uaa-auth-cf-space <%= esc(s) %> \
      <% end %> \
      --uaa-auth-cf-url <%= esc(p("uaa_auth.cf_api_url")) %> \
      --uaa-auth-cf-ca-cert $CF_CA_CERT \
      --generic-oauth-client-id <%= esc(p("generic_oauth.client_id")) %> \
      --generic-oauth-client-secret <%= esc(p("generic_oauth.client_secret")) %> \
      --generic-oauth-auth-url <%= esc(p("generic_oauth.auth_url")) %> \
      <% p("generic_oauth.auth_url_params").each do |k, v| %> \
      --generic-oauth-auth-url-param <%= esc(k) %>:<%= esc(v) %> \
      <% end %> \
      <% if_p("generic_oauth.scope") do |s| %> \
      --generic-oauth-scope <%= esc(s) %> \
      <% end %> \
      --generic-oauth-token-url <%= esc(p("generic_oauth.token_url")) %> \
      --generic-oauth-display-name <%= esc(p("generic_oauth.display_name")) %> \
      --session-signing-key $SIGNING_KEY \
      --resource-checking-interval <%= p("default_check_interval") %> \
      --old-resource-grace-period <%= p("old_resource_grace_period") %> \
      --resource-cache-cleanup-interval <%= p("resource_cache_cleanup_interval") %> \
      --cli-artifacts-dir /var/vcap/packages/fly \
      --yeller-api-key <%= esc(p("yeller.api_key")) %> \
      --yeller-environment <%= esc(p("yeller.environment_name")) %> \
      <% if_p("riemann.host", "riemann.port") do |host, port| %> \
      --riemann-host <%= esc(host) %> \
      --riemann-port <%= port.to_i %> \
      <% end %> \
      <% if_p("riemann.service_prefix") do |prefix| %> \
      --riemann-service-prefix <%= esc(prefix) %> \
      <% end %> \
      --metrics-host-name <%= name %>-<%= index %> \
      --metrics-attribute <%= esc("bosh-deployment:#{spec.deployment}") %> \
      --metrics-attribute <%= esc("bosh-job:#{name}") %> \
      <% p("riemann.tags").each do |k,v| %> \
      --metrics-attribute <%= esc(k) %>:<%= esc(v) %> \
      <% end %> \
      1>>$LOG_DIR/atc.stdout.log \
      2>>$LOG_DIR/atc.stderr.log

    ;;

  stop)
    kill_and_wait $PIDFILE

    ;;

  *)
    echo "Usage: $0 {start|stop}"

    ;;

esac
